<template>
  <div class="customer-contract-table">
    <div class="action-button-group">
      <el-dropdown trigger="click">
        <span class="el-dropdown-link cur-point">
          {{$t('common.base.moreOperator')}}
          <i class="iconfont icon-fdn-select"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <div @click="handleExport">{{$t('common.base.export')}}</div>
          </el-dropdown-item>
          <el-dropdown-item>
            <div @click="jumpContractList">{{$t('customer.detail.customerContractTable.jumpContractList')}}</div>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <span class="el-dropdown-link cur-point" @click="handleSelectColumn">
        {{$t('common.base.choiceCol')}}
        <i class="iconfont icon-fdn-select"></i>
      </span>
    </div>

    <el-table
      ref="tableRef"
      v-loading="listLoading"
      header-row-class-name="common-list-table-header__v2"
      :data="disposeFormListViewTime(dataList, columns)"
      stripe
      border
    >
      <template slot="empty">
        <BaseListForNoData
          v-show="!listLoading"
          table-type="smallTable"
          :notice-msg="$t('common.base.tip.noData')"
        ></BaseListForNoData>
      </template>

      <template v-for="column in columns">
        <el-table-column
          v-if="column && column.show"
          show-overflow-tooltip
          :align="column.align"
          :key="column.field"
          :label="column.displayName"
          :min-width="column.minWidth"
          :prop="column.field"
          :sortable="column.sortable"
          :width="column.width"
          :resizable="true"
        >
          <template slot-scope="scope">
            <template v-if="column.fieldName === 'contractNo'">
              <div class="link" @click="JumpContractDetail(scope.row)">
                {{ scope.row.contractNo || '' }}
              </div>
            </template>
            <template v-else-if="column.fieldName === 'customer'">
              {{ scope.row.customerVO.name || '' }}
            </template>
            <template v-else-if="column.fieldName === 'linkman'">
              {{ scope.row.linkManVO.name || '' }}
            </template>
            <!-- 服务部门 -->
            <template v-else-if="column.fieldName === 'tags'">
              {{ scope.row.tagList | tagName }}
            </template>
            <!-- 负责人 -->
            <template v-else-if="column.fieldName === 'managerPerson'">
              {{ scope.row.manager | tagName }}
            </template>
            <!-- 数据状态 -->
            <template v-else-if="column.fieldName === 'contractStatus'">
              <span
                class="status-tab"
                :style="activeStatus(scope.row.contractStatus)"
                >{{ getStatusValue[scope.row.contractStatus] }}</span
              >
            </template>
            <!-- 创建人 -->
            <template v-else-if="column.fieldName === 'creater'">
              {{ scope.row.createUser.displayName || '' }}
            </template>
            <template v-else-if="column.formType === 'product'">
              {{ scope.row.productVO | tagName }}
            </template>
            <template v-else>
              {{
                $formatFormField(column, scope.row, 'attributeMap')
              }}
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <!-- 分页 -->
    <BaseAddOnPagination :paginationInfo="paginationInfo" @pageJump="jump" @sizeChange="handleSizeChange" />

    <!-- 选择列 -->
    <biz-select-column ref="advanced" @save="saveColumnStatus" />

    <!-- 导出 -->
    <base-export-group
      ref="exportRef"
      :alert="exportAlert"
      :columns="exportColumnList"
      :build-params="exportParamsBuild"
      :group="true"
      :validate="exportCountCheck"
      method="post"
      action="/excels/contract/export"
    />
  </div>
</template>
<script>
import {
  ref,
  onMounted,
  reactive,
  toRefs,
  computed,
  nextTick,
} from 'vue';
import { contractFieldList, getContractField } from '@src/api/ContractApi';

import { storageGet, storageSet } from '@src/util/storage';
import { getThemeColor } from '@src/util/business/color'

import { Message } from 'element-ui';
import { t } from '@src/locales';

import {
  getCustomerOrProductFields,
  getStatusValue,
  getAdvancedFields,
} from '@src/modules/contract/contractList/fields';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { openAccurateTab, toast } from '@src/util/platform'
import { useFormTimezone, formatDate } from 'pub-bbx-utils'
const { disposeFormListViewTime } = useFormTimezone()

import { jumpContractDetail } from '@src/modules/contract/util/JumpContractUtil.js';


export default {
  name: 'customer-contract-table',
  filters: {
    tagName(value) {
      if (!value || !Array.isArray(value) || !value.length) return '';

      return value
        .filter(
          item =>
            (item && item.tagName) ||
            (item && item.displayName) ||
            (item && item.name)
        )
        .map(item => item.tagName || item.displayName || item.name)
        .join('，');
    },
  },
  props: {
    shareData: {
      type: Object,
      default: () => ({}),
    },
    type: {
      type: String,
      default: '',
    },
  },
  setup(props) {
    const advanced = ref(null);
    const exportRef = ref(null);

    const data = reactive({
      listLoading: true,
      columns: [], // 表头
      dataList: [], // 列表数据
      paginationInfo: {
        pageSize: 10,
        pageNum: 1,
        totalItems: 0,
      },
      productSubForm: [], // 导出列产品子表单数据
      systemForm: [], // 导出系统字段
    });

    const customerId = computed(() => {
      return props.shareData.customer.id || '';
    });

    const customerName = computed(() => {
      return props.shareData.customer.name || '';
    });

    const productId = computed(() => {
      return props.shareData?.product?.id || '';
    });

    const productName = computed(() => {
      return props.shareData?.product?.name || '';
    });

    // 数据状态的颜色
    const activeStatus = computed(() => {
      return val => {
        if (val == 'APPROVAL') {
          return { backgroundColor: '#448AFF' };
        } else if (val == 'EFFECTIVE') {
          return { backgroundColor: getThemeColor() };
        } else if (val == 'CLOSED') {
          return { backgroundColor: '#595959' };
        } else if (val == 'EXPIRED') {
          return { backgroundColor: '#595959' };
        } else if (val == 'DRAFT') {
          return { backgroundColor: '#595959' };
        }
      };
    });

    // 构建表格选择列字段
    const buildColumns = async () => {
      // 获取缓存在本地的选择列配置
      const localStorageData = await getLocalStorageData();
      const columnStatus = localStorageData.columnStatus || [];

      const localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});

      let customFields = [...data.columns];
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        // 有本地缓存--列表排序
        customFields = buildSortFields(customFields, localColumns);
      }

      const columns = customFields.map(col => {
        // 选择列配置 是否勾选（显示）&宽度
        let show = col.show === true;
        let width = col.width;
        let localField = localColumns[col.field]?.field || null;
        if (null != localField) {
          if (localField.width) {
            width =
              typeof localField.width == 'number'
                ? `${localField.width}px`
                : localField.width;
          }
          show = localField.show !== false;
        } 

        col.show = show;
        col.width = width;
        col.minWidth = col.width || 150;
        col.type = 'column';
        return col;
      });

      data.columns = [];
      nextTick(() => {
        data.columns = columns;
      });
    };

    // 选择列排序
    const buildSortFields = (originFields = [], fieldsMap = {}) => {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach(originField => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      return fields.concat(unsortedFields);
    };

    // 获取表头
    const getTableHeader = async () => {
      data.listLoading = true;
      let fields = [];
      try {
        let ret = await contractFieldList();

        if (ret.success) {
          // 过滤掉重复字段,系统字段，不需要显示的自定义字段
          const list = ret.result
            .filter(item =>
              item.formType != 'attachment' &&
              item.formType != 'autograph' &&
              item.formType != 'info' &&
              item.formType != 'separator'
            ).map(field => {
              return {
                ...field,
                tableName: 'contract',
                field: field.fieldName,
                label: field.displayName,
                formType: field.formType,
                minWidth: '150',
              };
            });
          fields = list
            .filter(item =>
              item.fieldName != 'contractNo' &&
              item.fieldName != 'contractName'
            )
            
          data.columns = [...getCustomerOrProductFields(), ...fields];

          // 导出系统字段
          data.systemForm = [...list, ...getAdvancedFields()];
          // 导出产品子表单的数据
          data.productSubForm = ret.result
            .filter(item => {
              return (
                item.formType === 'product' && item.subFormFieldList.length != 0
              );
            })[0]
            .subFormFieldList.map(p => {
              return {
                ...p,
                tableName: 'contract',
                field: p.fieldName,
                label: p.displayName,
              };
            });

          buildColumns();
        }
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        data.listLoading = false;
      }
    };

    // 获取列表数据
    const getTableList = () => {
      data.listLoading = true;
      data.dataList = [];
      try {
        getContractField({
          ...buildSearchParams(),
          pageNum: data.paginationInfo.pageNum,
          pageSize: data.paginationInfo.pageSize,
        }).then(res => {
          if (!res.success)
            return Message({
              message: res.message,
              type: 'error',
            });

          let { list, pageSize, pageNum, total } = res.result;

          data.dataList = list;

          data.paginationInfo = {
            pageSize,
            pageNum,
            totalItems: total,
          };

          data.listLoading = false;
        });
      } catch (error) {
        console.log('error=>', error);
      }
    };

    // 切换分页
    const jump = pN => {
      data.paginationInfo.pageNum = pN;
      getTableList();
    };

    const handleSizeChange = (pageSize) => {
      data.paginationInfo.pageSize = pageSize;
      data.paginationInfo.pageNum = 1;
      getTableList();
    }
    // 跳到合同详情页面
    const JumpContractDetail = row => {
      const { id } = row;

      if (!id) return;
      
      jumpContractDetail(row)
    };

    // 跳转到合同列表页面
    const jumpContractList = () => {
      let params = '';
      if (props.type === 'customerContract') {
        params = `customerId=${customerId.value}&customerName=${customerName.value}`;
      } else {
        params = `productId=${productId.value}&productName=${productName.value}`;
      }
      openAccurateTab({
        type: PageRoutesTypeEnum.PageContractList,
        params,
        reload: true,
      });
    };

    // ======================= 选择列start
    // 获取本地localstorage
    const getLocalStorageData = () => {
      const dataStr = storageGet('customer_contract_list', '{}');
      return JSON.parse(dataStr);
    };

    // 保存数据到本地localstorage
    const saveDataToStorage = (key, value) => {
      const data = getLocalStorageData();
      data[key] = value;
      storageSet('customer_contract_list', JSON.stringify(data));
    };

    // 点击选择列
    const handleSelectColumn = () => {
      // 先把模板id去掉，不传到选择列组件里面，选择列组件对模板id做了处理
      let arr = data.columns.map(item => {
        const { templateId, ...other } = item;
        return {
          ...other
        }
      })
      advanced.value.open(arr);
    };

    // 保存选择列
    const saveColumnStatus = event => {
      let columns = event.data || [];
      data.columns = [];
      nextTick(() => {
        data.columns = columns.slice();
        saveColumnStatusToStorage();
      });
      Message({
        message: t('common.base.saveSuccess'),
        type: 'success',
      });
    };

    // 保存选择列配置到本地
    const saveColumnStatusToStorage = () => {
      const localStorageData = getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = data.columns.map(c => ({
        field: c.fieldName,
        show: c.show,
        width: c.width,
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      saveDataToStorage('columnStatus', columnsStatus);
    };
    // ======================= 选择列end

    // ================== 导出Start
    const exportColumnList = computed(() => {
      const systemInfo = {
        label: t('contract.list.systemInfoLabel'),
        value: 'systemChecked',
        columns: [...data.systemForm].map(item => {
          item.export = true;
          item.label = item.displayName;
          return item;
        }),
      };

      // 产品子表单
      const productInfo = {
        label: t('contract.list.productInfoLabel'),
        value: 'productSubChecked',
        columns: data.productSubForm.map(item => {
          item.export = true;
          item.label = item.displayName;
          return item;
        }),
      };

      let column = [systemInfo, productInfo].filter(item => {
        return item.columns && item.columns.length > 0;
      });

      return column;
    });

    // 导出提示
    const exportAlert = (result, params = {}) => {
      toast(result.message, result.status === 0 ? 'success' : 'error');
    };

    // 导出客户或者产品的全部合同
    const handleExport = () => {
      let fileName = `${formatDate(
        new Date(),
        t('contract.list.handleExport.exportFileName', {date: 'YYYY-MM-DD'})
      )}`;

      exportRef.value.open([], fileName, false);
    };

    // 构建导出参数
    const exportParamsBuild = (checkedMap, ids) => {
      let { productSubChecked, systemChecked } = checkedMap || {};
      let checkArr = [...productSubChecked, ...systemChecked];
      return {
        ...buildSearchParams(),
        id: ids,
        fieldList: checkArr || [],
        totalCount: data.paginationInfo.totalItems,
      };
    };

    /**  构建搜索参数 */
    const buildSearchParams = () => {
      const obj = {
        tags: [],
        searchListFormList: [],
        likeSearch: '',
        pageSize: 10,
        pageNum: 1,
        column: '',
        asc: true,
        contractStatus: '',
        searchType: '',
        total: data.paginationInfo.totalItems,
        templateId: '',
      }
      props.type === 'customerContract'
          ? (obj.customerId = customerId.value)
          : (obj.product = [productId.value])
      return obj;
    };

    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    const exportCountCheck = (ids, max) => {
      let exportAll = !ids || ids.length == 0;

      return exportAll && data.paginationInfo.totalItems > max
        ? t('common.base.tip.exportLimit', { max })
        : null;
    };
    // ================== 导出Start

    onMounted(async () => {
      await getTableList();
      await getTableHeader();
    });

    return {
      JumpContractDetail,
      jumpContractList,
      advanced,
      ...toRefs(data),
      activeStatus,
      jump,
      handleSizeChange,
      handleSelectColumn,
      saveColumnStatus,
      getStatusValue,
      disposeFormListViewTime,
      exportRef,
      exportColumnList,
      exportAlert,
      handleExport,
      exportParamsBuild,
      buildSearchParams,
      exportCountCheck,
    };
  },
};
</script>
<style lang="scss" scoped>
.customer-contract-table {
  padding: 12px;
  .action-button-group {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 12px;
    padding: 0;
  }
  .link {
    color: $color-primary-light-6;
    cursor: pointer;
    &:hover {
      text-decoration: underline;
    }
  }
  .status-tab {
    display: inline-block;
    min-width: 52px;
    max-width: 128px;
    height: 22px;
    line-height: 22px;
    padding: 0 8px;
    font-size: 12px;
    border-radius: 11px;
    text-align: center;
    vertical-align: middle;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    color: #fff;
  }
}
</style>